package com.filemanage.file;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;


import com.filemanage.util.MyFileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import net.sf.json.JSONObject;
import sun.misc.Request;

@RestController
public class UploadController {
	@Value("${windows_server.filepath}")
    String FILEPATH;

    @Value("${windows_server.filepath}")
    String windows_filepath;

    @Value("${linux_server.filepath}")
    String linux_filepath;

	//zip文件解压路径
	 String REPORT_ZIP_PATH;
	 String REPORT_HTML_PATH;


    public void setFilepath() {
     	String osType=System.getProperty("os.name");
    	if(osType.startsWith("Win")) {
    		FILEPATH=windows_filepath;
    	}else {
    		FILEPATH=linux_filepath;
    	}
    	REPORT_ZIP_PATH=FILEPATH+"autoops/report_zip/";
    	REPORT_HTML_PATH=FILEPATH+"autoops/report_html/";
    }

    //文件下载相关代码
    @RequestMapping("/index")
    public String downloadFile(){

        return ParamInit.REPORT_HTML_PATH;
    }


    @RequestMapping(value = "/FILE/upload/{project}",method = RequestMethod.POST)
    @Transactional
    public ResponseEntity<?> uploadFile(Model model,@RequestParam("file") MultipartFile file,
    		HttpServletRequest request,@PathVariable String project){
		if(!limitFile(file,500)){
			return new ResponseEntity(HttpStatus.NO_CONTENT);
		}
    	setFilepath();
    	 String module=request.getParameter("module");
    	 /**
    	  * 客户端自定义文件名称
    	  */
    	 String myfilename=request.getParameter("filename");
        String fileRealName = file.getOriginalFilename();
        System.out.println("fileRealName-->" + fileRealName);
        byte[] bytes=null;
		try {
			bytes = file.getBytes();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//        Path path = Paths.get(ParamInit.FILEPATH + file.getOriginalFilename());
        System.out.println(bytes.length);
        String fileNewName=MyFileUtil.getNewFileName();
        String extenName=MyFileUtil.getFileExten4Str(fileRealName);
        String FILEPATH_="";
        if(module!=null) {
       	  FILEPATH_ =ParamInit.FILEPATH+project+"/"+module+"/";
        }else {
       	  FILEPATH_ =ParamInit.FILEPATH+project+"/";
        }
        MyFileUtil.createDir(FILEPATH_);

        /*
         * 使用客户端传输的文件名
         * 否则系统自动生成唯一文件名
         */
        if(myfilename!=null) {
        	fileNewName=myfilename;
        }
        Path  path = Paths.get(FILEPATH_ + fileNewName+extenName);
        try {
			Files.write(path, bytes);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        String fileExten=MyFileUtil.getFileExten(FILEPATH_ + file.getOriginalFilename());

//        FileUpload fld=new FileUpload();
//        fld.setFilename(fileNewName+extenName);
//        fld.setOriginalfilename(fileName);
//        fld.setPath(FILEPATH);
//        fld.setExtenname(extenName);
//        fld.setProject(project);
//        fld.setModule(module);
//        service.insert(fld);
		Map<String,Object> map = new HashMap<>();
		map.put("originalfilename",fileRealName);
		map.put("filename",fileNewName+extenName);


		// return new ResponseEntity<Object>("{originalfilename:'"+fileRealName+"',filename:'"+
		//         fileNewName+extenName+"'}", new HttpHeaders(), HttpStatus.OK);
		return new ResponseEntity<Object>(map, new HttpHeaders(), HttpStatus.OK);
    }


     /**
      * 上传報表文件： 先保存在临时目录，用户确认后再拷贝到指定目录
      * @param model
      * @param file
      * @param request
      * @param project
      * @return
      * @throws IOException
      */
	 @RequestMapping(value = "/FILE/uploadReport/{project}")
	 @Transactional
	 public ResponseEntity<?> uploadReportFile(Model model,@RequestParam("file") MultipartFile file,
			 HttpServletRequest request,@PathVariable String project){
		 if(!limitFile(file,20)){
			 return new ResponseEntity(HttpStatus.NO_CONTENT);
		 }
		 setFilepath();
    	 String module=request.getParameter("module");
    	 /**
    	  * 客户端自定义文件名称
    	  */
    	 String myfilename=request.getParameter("filename");
    	 String fileRealName = file.getOriginalFilename();
    	 System.out.println("fileRealName-->" + fileRealName);
    	 byte[] bytes=null;
		try {
			bytes = file.getBytes();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//        Path path = Paths.get(ParamInit.FILEPATH + file.getOriginalFilename());
    	 System.out.println(bytes.length);
    	 String fileNewName=MyFileUtil.getNewFileName();
    	 String extenName=MyFileUtil.getFileExten(fileRealName);
    	 String FILEPATH_="";
    	 if(module!=null) {
    		 FILEPATH_ =ParamInit.FILEPATH+project+"/"+module+"/";
    	 }else {
    		 FILEPATH_ =ParamInit.FILEPATH+project+"/";
    	 }
    	 MyFileUtil.createDir(FILEPATH_);

    	 /*
    	  * 使用客户端传输的文件名
    	  * 否则系统自动生成唯一文件名
    	  */
    	 if(myfilename!=null) {
    		 fileNewName=myfilename;
    	 }
    	 Path  path = null;
    	 if("\\.html".equals(extenName)) {
    		 path=Paths.get(FILEPATH_ + fileNewName+extenName);
    	 }else {
    		 path=Paths.get(FILEPATH_ + fileNewName+extenName);
    	 }

    	 try {
			Files.write(path, bytes);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    	 Map<String,Object> map=new HashMap<String,Object>();
    	 System.out.println(extenName);
    	 if(extenName.contains("html")) {
    		 List<String> list=new ArrayList<String>();
   		  map.put("fileabsolutepath", fileRealName);
   		  list.add("/"+fileNewName+extenName);
   	      map.put("arrlist", list);
          map.put("file_sum_desc", "选中1个html文件");
    	 }else {
    		 map=opt_report(fileNewName+extenName);
    	 }

    	 JSONObject jsonObj = new JSONObject();
    	 Map <String, Object> ingredients = new HashMap <String, Object>();
    	 ingredients.put("filerealname", fileRealName);
    	 ingredients.put("filelogicname", fileNewName+extenName);
    	 ingredients.put("fileinfo", map);
    	 jsonObj.put("obj", ingredients);

    	 return new ResponseEntity<Object>(jsonObj.toString(), new HttpHeaders(), HttpStatus.OK);
     }


     /**
      * 上传发布文件： 先保存在临时目录，用户确认后再拷贝到指定目录
      * @param model
      * @param file
      * @param request
      * @param project
      * @return
      * @throws IOException
      */
	 @RequestMapping(value = "/FILE/uploadPublish/{project}")
	 @Transactional
	 public ResponseEntity<?> uploadPublishFile(Model model,@RequestParam("file") MultipartFile file,
			 HttpServletRequest request,@PathVariable String project){
		 setFilepath();
		 String module=request.getParameter("module");
		 module = "publish/"+module;

    	if(!limitFile(file,500)){
    		return new ResponseEntity(HttpStatus.NO_CONTENT);
		}

		 /**
		  * 客户端自定义文件名称
		  */
		 String myfilename=request.getParameter("filename");
		 String fileRealName = file.getOriginalFilename();
		 System.out.println("fileRealName-->" + fileRealName);
		 byte[] bytes=null;
	/*	 try {
			 bytes = file.getBytes();
		 } catch (IOException e) {
			 // TODO Auto-generated catch block
			 e.printStackTrace();
		 }*/
		 String fileNewName=MyFileUtil.getNewFileName();
		 String extenName=MyFileUtil.getFileExten4Str(fileRealName);
		 String FILEPATH_="";
		 if(module!=null) {
			 FILEPATH_ =ParamInit.FILEPATH+project+"/"+module+"/";
		 }else {
			 FILEPATH_ =ParamInit.FILEPATH+project+"/";
		 }
		 MyFileUtil.createDir(FILEPATH_);



		 if(myfilename!=null) {
			 fileNewName=myfilename;
		 }
		 Path  path = Paths.get(FILEPATH_ + fileNewName+extenName);
		 try {
//			 Files.write(path, bytes);
			 file.transferTo(new File(FILEPATH_ + fileNewName+extenName));
		 } catch (IOException e) {
			 // TODO Auto-generated catch block
			 e.printStackTrace();
		 }
		 String fileExten=MyFileUtil.getFileExten(FILEPATH_ + file.getOriginalFilename());
		 return new ResponseEntity<Object>("{originalfilename:'"+fileRealName+"',filename:'"+
				 fileNewName+extenName+"'}", new HttpHeaders(), HttpStatus.OK);
     }

     public Map<String,Object> opt_report(String filename) {

		 Map<String,Object> map=new HashMap<String,Object>();
	 	/*
		HanyuPinyinHelper hanyuPinyinHelper = new HanyuPinyinHelper() ;
//		 System.out.println(hanyuPinyinHelper.isSpecialChar(msg));

     	String fileAddress = ParamInit.REPORT_ZIP_PATH+filename;

        String copyAddress = "";


        CompressUtil.unZipFiles(fileAddress,ParamInit.REPORT_ZIP_PATH);

        String[] strArr=filename.split("\\.");

         filename=strArr[0];

         if(filename!=null) {
         	copyAddress=ParamInit.REPORT_HTML_PATH+filename+"/";
         }
//         MyFileUtil.copyDir(ParamInit.REPORT_ZIP_PATH+filename, copyAddress);

         List<File> files = MyFileUtil.searchFiles(new File(ParamInit.REPORT_ZIP_PATH+filename), ".htm");

         StringBuffer sbf=new StringBuffer();
         List<String> arrlist=new ArrayList<String>();
         	sbf.append("本次上传:" + files.size() + "个html文件");
      		sbf.append("</br>");
         System.out.println("本次上传:" + files.size() + "个html文件");
         for (File file : files) {
 			String absolutefile=file.getAbsolutePath();
 			absolutefile=absolutefile.substring(ParamInit.REPORT_HTML_PATH.length()-2, absolutefile.length());
 			absolutefile=absolutefile.replace("\\", "/");
			 absolutefile = hanyuPinyinHelper.toHanyuPinyin(absolutefile);
 			sbf.append(absolutefile);
         	arrlist.add(absolutefile);
         	sbf.append("</br>");
         }
         map.put("fileabsolutepath", sbf.toString());
         map.put("file_sum_desc", "所选文件含有"+files.size() + "个html文件");
         map.put("arrlist", arrlist);
     	*/
     	return map;

     }

     public static byte[] getUTF8BytesFromGBKString(String gbkStr) {
         int n = gbkStr.length();
         byte[] utfBytes = new byte[3 * n];
         int k = 0;
         for (int i = 0; i < n; i++) {
             int m = gbkStr.charAt(i);
             if (m < 128 && m >= 0) {
                 utfBytes[k++] = (byte) m;
                 continue;
             }
             utfBytes[k++] = (byte) (0xe0 | (m >> 12));
             utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
             utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
         }
         if (k < utfBytes.length) {
             byte[] tmp = new byte[k];
             System.arraycopy(utfBytes, 0, tmp, 0, k);
             return tmp;
         }
         return utfBytes;
     }

     @PostMapping(value = "/FILE/reportFileEffective/{project}")
	public String reportFileEffective(HttpServletRequest request,@PathVariable String project,@RequestBody String param){
    	 setFilepath();
		JSONObject jsonObject = JSONObject.fromObject(param);
		String para1=(String)jsonObject.get("params");
		String filename=null;
		filename=para1;
		if(filename!=null) {
	    	 String[] arrfilename=filename.split("\\.");
	    	 filename=arrfilename[0];
	    	 System.out.print("--------------");
	    	 System.out.println(filename);
		}

		String extname=MyFileUtil.getFileExten(para1);

		if(extname.contains("zip")) {
			MyFileUtil.copyDir(ParamInit.REPORT_ZIP_PATH + filename, ParamInit.REPORT_HTML_PATH + filename + "/");
		}else {
			MyFileUtil.copyFile(ParamInit.REPORT_ZIP_PATH + para1, ParamInit.REPORT_HTML_PATH + para1,true);
		}

		List<File> files = MyFileUtil.searchFiles(new File(ParamInit.REPORT_HTML_PATH + filename), ".htm");

		StringBuffer sbf = new StringBuffer();
		List<String> arrlist = new ArrayList<String>();
		sbf.append("本次上传:" + files.size() + "个html文件");
		sbf.append("</br>");
		System.out.println("本次上传:" + files.size() + "个html文件");
		for (File file : files) {
			String absolutefile=file.getAbsolutePath();
			absolutefile=absolutefile.substring(ParamInit.REPORT_HTML_PATH.length()-2, absolutefile.length());
			absolutefile=absolutefile.replace("\\", "/");
			sbf.append(absolutefile);
//			arrlist.add(file.getName());
			arrlist.add(absolutefile);
		}

		// MyFileUtil.delFolder(fileAddress);
		if(extname.contains("html")) {
			arrlist.add(para1);
		}

		if(arrlist.size()>0) {
			MyFileUtil.delFolder(ParamInit.REPORT_ZIP_PATH);
			MyFileUtil.changeDirtoPinyin(ParamInit.REPORT_HTML_PATH + filename);
		}


		return String.valueOf(arrlist.size());
	}


     /**
      * 针对个别业务加上去的
      * @param model
      * @param file
      * @param request
      * @param project
      * @return
      * @throws IOException
      */
     @RequestMapping(value = "/FILE/uploadDB/{project}")
     public ResponseEntity<?> uploadDBFile(Model model,@RequestParam("file") MultipartFile file,
    		 HttpServletRequest request,@PathVariable String project)  {

		 if(!limitFile(file,20)){
			 return new ResponseEntity(HttpStatus.NO_CONTENT);
		 }
    	 setFilepath();
    	 String module=request.getParameter("module");
    	 String fileName = file.getOriginalFilename();
    	 System.out.println("fileName-->" + fileName);
    	 byte[] bytes=null;
		try {
			bytes = file.getBytes();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//        Path path = Paths.get(ParamInit.FILEPATH + file.getOriginalFilename());
    	 System.out.println(bytes.length);
    	 String fileNewName=MyFileUtil.getNewFileName();
    	 String extenName=MyFileUtil.getFileExten4Str(fileName);
    	 String FILEPATH_="";
    	 if(module!=null) {
    		 FILEPATH_ =ParamInit.FILEPATH+project+"/"+module+"/";
    	 }else {
    		 FILEPATH_ =ParamInit.FILEPATH+project+"/";
    	 }
    	 MyFileUtil.createDir(FILEPATH_);
    	 Path path = Paths.get(FILEPATH_ + fileNewName+extenName);
    	 try {
			Files.write(path, bytes);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	 String fileExten= MyFileUtil.getFileExten(FILEPATH_ + file.getOriginalFilename());

         return new ResponseEntity<Object>("{project:'" +project+"',module:'"+module+"',originalfilename:'"+fileName+"',filename:'"+
                 fileNewName+extenName+"'}", new HttpHeaders(), HttpStatus.OK);
     }



    private boolean limitFile(MultipartFile file,int LIMIT_SIZE){
     	boolean state=false;
		Double d=new Double(file.getSize());
		Double fileSize = new Double(d/1048576);
		int size = (int)Math.ceil(d/1048576);
		if(size<=LIMIT_SIZE){
			state=true;
		}
		return state;
	}

}